from django.shortcuts import render
from django.views import View
from django import http
from alipay import AliPay
from alipay.utils import AliPayConfig
from django.conf import settings
from orders.models import OrderInfo
from pays.models import PayModel

# 1，支付页面处理
class AliPayMentView(View):
    def get(self,request,order_id):

        # 判断改订单是否已经支付过
        if PayModel.objects.filter(out_trade_no_id=order_id).count() > 0:
            return http.JsonResponse({"code": 4002, "errmsg": "该订单已支付过"})

        # 0,校验订单是否存在
        try:
            order = OrderInfo.objects.get(order_id=order_id,status=1)
        except OrderInfo.DoesNotExist as e:
            return http.JsonResponse({"code":4001,"errmsg":"订单不存在"})


        # 1,读取私钥，支付宝公钥
        # app_private_key_string = open("PMSP/utils/keys/app_private_key.pem").read()
        # alipay_public_key_string = open("PMSP/utils/keys/alipay_public_key.pem").read()

        # 2，创建alipay对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=settings.ALIPAY_NOTIFY_URL,  # the default notify path
            app_private_key_string=open(settings.ALIPAY_PRIVATE_KEY_PATH).read(),
            # alipay public key, do not use your own public key!
            alipay_public_key_string=open(settings.ALIPAY_PUBLIC_KEY_PATH).read(),
            sign_type=settings.ALIPAY_SIGN_TYPE,  # RSA or RSA2
            debug=settings.ALIPAY_DEBUG,  # False by default
            verbose=settings.ALIPAY_VERBOSE,  # useful for debugging
            config=AliPayConfig(timeout=15)  # optional, request timeout
        )

        # 3,创建支付链接
        subject = "PMSP购物商城"
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount + order.feight),
            subject=subject,
            return_url=settings.ALIPAY_RETURN_URL,
        )

        alipay_url = "https://openapi.alipaydev.com/gateway.do" + "?" + order_string


        return http.JsonResponse({"code":0,"alipay_url":alipay_url})

# 2,订单状态更改
class AliPayOrderChangeView(View):
    def get(self,request):

        # 1,获取参数
        dict_data =  request.GET.dict()
        signature = dict_data.pop("sign")
        order_id = dict_data.get("out_trade_no")
        trade_no = dict_data.get("trade_no")

        # 2，校验数据
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=settings.ALIPAY_NOTIFY_URL,  # the default notify path
            app_private_key_string=open(settings.ALIPAY_PRIVATE_KEY_PATH).read(),
            # alipay public key, do not use your own public key!
            alipay_public_key_string=open(settings.ALIPAY_PUBLIC_KEY_PATH).read(),
            sign_type=settings.ALIPAY_SIGN_TYPE,  # RSA or RSA2
            debug=settings.ALIPAY_DEBUG,  # False by default
            verbose=settings.ALIPAY_VERBOSE,  # useful for debugging
            config=AliPayConfig(timeout=15)  # optional, request timeout
        )
        if not alipay.verify(dict_data, signature):
            return http.HttpResponseForbidden("订单信息被篡改")

        # 3，更新订单状态
        order = OrderInfo.objects.get(order_id=order_id,status__lt=5)
        order.status += 1
        order.save()

        # 3,1 保存支付宝订单数据
        PayModel.objects.create(
            trade_no=trade_no,
            out_trade_no=order
        )

        # 4，返回响应
        context = {
            "order_id":order_id
        }
        return render(request,template_name='pay_success.html',context=context)
